﻿using Common.Core.Util;
using Common.Helpers;
using SqlSugar;
using SqlSugar.IOC;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data;
using System.Linq.Expressions;
using System.Reflection;
using System.Text.RegularExpressions;

namespace Common.Core.Data.SqlSugar
{
    public class SugarRepository<T, TKey> : SimpleClient<T>, IRepository<T, TKey> where T : Entity, new()
    {
        /// <summary>
        /// 获取访问数据库配置
        /// </summary>
        protected global::SqlSugar.DbType curDbType;

        //注意这里要有默认值等于null，默认值不能少，不然无参方式 IOC 不好注入
        public SugarRepository(ISqlSugarClient context = null) : base(context)
        {
            if (context == null)
            {
                base.Context = DbScoped.SugarScope;
                curDbType = base.Context.CurrentConnectionConfig.DbType;
            }
        }

        /// <summary>
        /// 排序字段
        /// </summary>
        protected string sortField;

        /// <summary>
        /// 排序字段
        /// </summary>
        public string SortField
        {
            get
            {
                return sortField;
            }
            set
            {
                sortField = value;
            }
        }

        /// <summary>
        /// 是否为降序
        /// </summary>
        protected bool isDescending = true;

        /// <summary>
        /// 选择的字段，默认为所有(*) 
        /// </summary>
        protected string selectedFields = " * ";

        /// <summary>
        /// 需要初始化的对象表名
        /// </summary>
        protected string tableName = typeof(T).GetCustomAttribute<TableAttribute>(false)?.Name;

        /// <summary>
        /// 事务
        /// </summary>
        public IDbTransaction DbTransaction { get; set; }

        /// <summary>
        /// 开启事务
        /// </summary>
        public virtual IDbTransaction BeginTransaction()
        {
            base.Context.Ado.BeginTran();

            return DbTransaction = base.Context.Ado.Transaction;
        }

        /// <summary>
        /// 事务提交
        /// </summary>
        public virtual void CommitTransaction()
        {
            base.Context.Ado.CommitTran();
        }

        /// <summary>
        /// 事务回滚
        /// </summary>
        public virtual void RollBackTransaction()
        {
            base.Context.Ado.RollbackTran();
        }

        #region 新增

        /// <summary>
        /// 新增
        /// </summary>
        /// <param name="entity"></param>
        /// <param name="trans">事务对象</param>
        /// <returns></returns>
        public virtual int Insert(T entity, IDbTransaction trans = null)
        {
            return base.Insert(entity) ? 1 : 0;
        }

        /// <summary>
        /// 异步新增
        /// </summary>
        /// <param name="entity"></param>
        /// <param name="trans">事务对象</param>
        /// <returns></returns>
        public virtual async Task<int> InsertAsync(T entity, IDbTransaction trans = null)
        {
            return await base.InsertAsync(entity) ? 1 : 0;
        }

        /// <summary>
        /// 批量插入数据
        /// </summary>
        /// <param name="entities"></param>
        /// <returns>执行成功返回<c>true</c>，否则为<c>false</c>。</returns>
        public virtual void Insert(List<T> entities, IDbTransaction trans = null)
        {
            base.InsertRange(entities);
        }

        /// <summary>
        /// 异步新增
        /// </summary>
        /// <param name="entity"></param>
        /// <param name="trans">事务对象</param>
        /// <returns></returns>
        public virtual async Task<int> InsertAsync(List<T> entities, IDbTransaction trans = null)
        {
            return await base.InsertRangeAsync(entities) ? 1 : 0;
        }

        #region 新增扩展

        /// <summary>
        /// 异步批量新增实体
        /// </summary>
        /// <param name="entities"></param>
        /// <returns>执行成功返回<c>true</c>，否则为<c>false</c>。</returns>
        public virtual async void InsertAsync(List<T> entities)
        {
            await base.InsertRangeAsync(entities);
        }
        /// <summary>
        /// 批量新增SqlBulk方式，效率最高
        /// </summary>
        /// <param name="entities">数据实体集合</param>
        /// <param name="destinationTableName">数据库表名称，默认为实体名称</param>
        public virtual void InsertBulk(IList<T> entities, string destinationTableName = null)
        {
            //base.InsertRangeAsync(entities.ToArray());
            //分页插入 ，如果不支持db.Fastest分页插入也是可以提升一下性能的
            base.Context.Utilities.PageEach(entities, 1000, pageList => {
                base.Context.Insertable(pageList).ExecuteCommand();
                //db.Insertable(List<实体>).UseParameter().ExecuteCommand() 可以试试和上面哪个性能高用哪个
            });

            //DbContext.BulkInsert<T>(entities, destinationTableName);
        }
        /// <summary>
        /// 执行新增的sql语句
        /// </summary>
        /// <param name="sql">新增Sql语句</param>
        /// <returns></returns>
        [Obsolete("建议用SqlSugar官方的函数，或者做好sql注入检查")]
        public int InsertBySql(string sql)
        {
            return base.Context.Ado.ExecuteCommand(sql);
        }
        #endregion

        #endregion

        #region 删除

        /// <summary>
        /// 同步物理删除实体。
        /// </summary>
        /// <param name="entity">实体</param>
        /// <returns></returns>
        public virtual bool Delete(T entity, IDbTransaction trans = null)
        {
            return base.Delete(entity);
        }

        /// <summary>
        /// 异步物理删除实体。
        /// </summary>
        /// <param name="entity">实体</param>
        /// <param name="trans">事务对象</param>
        /// <returns></returns>
        public virtual async Task<bool> DeleteAsync(T entity, IDbTransaction trans = null)
        {
            return await base.DeleteAsync(entity);
        }

        /// <summary>
        /// 物理删除信息
        /// </summary>
        /// <param name="primaryKey"></param>
        /// <param name="trans">事务对象</param>
        /// <returns>执行成功返回<c>true</c>，否则为<c>false</c>。</returns>
        public virtual bool Delete(TKey primaryKey, IDbTransaction trans = null)
        {
            return base.DeleteById(primaryKey);
        }
        /// <summary>
        /// 异步物理删除信息
        /// </summary>
        /// <param name="primaryKey"></param>
        /// <param name="trans">事务对象</param>
        /// <returns>执行成功返回<c>true</c>，否则为<c>false</c>。</returns>
        public virtual async Task<bool> DeleteAsync(TKey primaryKey, IDbTransaction trans = null)
        {
            return await base.DeleteByIdAsync(primaryKey);
        }

        /// <summary>
        /// 按主键批量删除
        /// </summary>
        /// <param name="ids">主键Id List集合</param>
        /// <param name="trans">事务对象</param>
        /// <returns>执行成功返回<c>true</c>，否则为<c>false</c>。</returns>
        public virtual bool DeleteBatch(IList<dynamic> ids, IDbTransaction trans = null)
        {
            return base.DeleteByIds(ids.ToArray());
        }
        /// <summary>
        /// 按条件批量删除
        /// </summary>
        /// <param name="where">条件</param>
        /// <param name="trans">事务对象</param>
        /// <returns>执行成功返回<c>true</c>，否则为<c>false</c>。</returns>
        [Obsolete("建议用SqlSugar官方的函数")]
        public virtual bool DeleteBatchWhere(string where, IDbTransaction trans = null)
        {
            if (HasInjectionData(where))
            {
                LogHelper.Info($"检测出SQL注入的恶意数据(IP:{Function.GetIPAddress()}), {where}");
                throw new Exception("检测出SQL注入的恶意数据");
            }
            if (string.IsNullOrEmpty(where))
            {
                where = "1=1";
            }
            string sql = $"delete from {tableName} where " + where;

            base.Context.Ado.ExecuteCommand(sql);
            return true;

        }
        /// <summary>
        /// 按条件批量删除
        /// </summary>
        /// <param name="where">条件</param>
        /// <param name="trans">事务对象</param>
        /// <returns>执行成功返回<c>true</c>，否则为<c>false</c>。</returns>
        [Obsolete("建议用SqlSugar官方的函数")]
        public virtual async Task<bool> DeleteBatchWhereAsync(string where, IDbTransaction trans = null)
        {
            if (HasInjectionData(where))
            {
                LogHelper.Info($"检测出SQL注入的恶意数据(IP:{Function.GetIPAddress()}), {where}");
                throw new Exception("检测出SQL注入的恶意数据");
            }
            if (string.IsNullOrEmpty(where))
            {
                where = "1=1";
            }
            string sql = $"delete from {tableName} where " + where;

            await base.Context.Ado.ExecuteCommandAsync(sql);
            return true;
        }

        #region 删除扩展
        /// <summary>
        /// 执行删除数据Sql语句
        /// </summary>
        /// <param name="sql">删除的Sql语句</param>
        /// <returns></returns>
        public int DeleteBySql(string sql)
        {
            return base.Context.Ado.ExecuteCommand(sql);
        }
        #endregion

        #endregion

        #region 更新操作

        #region 更新实体或批量更新
        /// <summary>
        /// 更新
        /// </summary>
        /// <param name="entity"></param>
        /// <param name="trans">事务对象</param>
        /// <returns>执行成功返回<c>true</c>，否则为<c>false</c>。</returns>
        public virtual bool Update(T entity, IDbTransaction trans = null)
        {
            return base.Update(entity);
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="entity"></param>
        /// <param name="trans">事务对象</param>
        /// <returns>执行成功返回<c>true</c>，否则为<c>false</c>。</returns>
        public virtual async Task<bool> UpdateAsync(T entity, IDbTransaction trans = null)
        {
            return await base.UpdateAsync(entity);
        }
        /// <summary>
        /// 批量更新数据(待验证)
        /// </summary>
        /// <param name="entities"></param>
        /// <param name="trans">事务对象</param>
        /// <returns>执行成功返回<c>true</c>，否则为<c>false</c>。</returns>
        public virtual bool Update(List<T> entities, IDbTransaction trans = null)
        {
            return base.UpdateRange(entities);
        }
        #endregion

        #region 更新某一字段值
        /// <summary>
        /// 更新某一字段值,字段值字符类型
        /// </summary>
        /// <param name="strField">字段</param>
        /// <param name="fieldValue">字段值字符类型</param>
        /// <param name="where">条件,为空更新所有内容</param>
        /// <param name="trans">事务对象</param>
        /// <returns>执行成功返回<c>true</c>，否则为<c>false</c>。</returns>
        [Obsolete("建议用SqlSugar官方的函数")]
        public virtual bool UpdateTableField(string strField, string fieldValue, string where, IDbTransaction trans = null)
        {
            if (HasInjectionData(where))
            {
                LogHelper.Info($"检测出SQL注入的恶意数据(IP:{Function.GetIPAddress()}), {where}");
                throw new Exception("检测出SQL注入的恶意数据");
            }
            if (string.IsNullOrEmpty(where))
            {
                where = "1=1";
            }
            string sql = $"update {tableName} set " + strField + "='" + fieldValue + "'";
            if (!string.IsNullOrEmpty(where))
            {
                sql += " where " + where;
            }

            base.Context.Ado.ExecuteCommand(sql);
            return true;
        }
        /// <summary>
        /// 更新某一字段值（用来做数字累加）
        /// </summary>
        /// <param name="strField">字段</param>
        /// <param name="fieldValue">字段值字符类型</param>
        /// <param name="where">条件,为空更新所有内容</param>
        /// <param name="trans">事务对象</param>
        /// <returns>执行成功返回<c>true</c>，否则为<c>false</c>。</returns>
        [Obsolete("建议用SqlSugar官方的函数")]
        public virtual bool UpdateTableField_V2(string strField, string fieldValue, string where, IDbTransaction trans = null)
        {
            if (HasInjectionData(where))
            {
                LogHelper.Info($"检测出SQL注入的恶意数据(IP:{Function.GetIPAddress()}), {where}");
                throw new Exception("检测出SQL注入的恶意数据");
            }
            if (string.IsNullOrEmpty(where))
            {
                where = "1=1";
            }
            string sql = $"update {tableName} set " + strField + "=" + fieldValue + "";
            if (!string.IsNullOrEmpty(where))
            {
                sql += " where " + where;
            }

            base.Context.Ado.ExecuteCommand(sql);
            return true;
        }
        /// <summary>
        /// 更新某一字段值,字段值字符类型
        /// </summary>
        /// <param name="strField">字段</param>
        /// <param name="fieldValue">字段值字符类型</param>
        /// <param name="where">条件,为空更新所有内容</param>
        /// <param name="trans">事务对象</param>
        /// <returns>执行成功返回<c>true</c>，否则为<c>false</c>。</returns>
        [Obsolete("建议用SqlSugar官方的函数")]
        public virtual async Task<bool> UpdateTableFieldAsync(string strField, string fieldValue, string where, IDbTransaction trans = null)
        {
            if (HasInjectionData(where))
            {
                LogHelper.Info($"检测出SQL注入的恶意数据(IP:{Function.GetIPAddress()}), {where}");
                throw new Exception("检测出SQL注入的恶意数据");
            }
            if (string.IsNullOrEmpty(where))
            {
                where = "1=1";
            }
            string sql = $"update {tableName} set " + strField + "='" + fieldValue + "'";
            if (!string.IsNullOrEmpty(where))
            {
                sql += " where " + where;
            }

            await base.Context.Ado.ExecuteCommandAsync(sql);
            return true;
        }
        /// <summary>
        /// 更新某一字段值，字段值为数字
        /// </summary>
        /// <param name="strField">字段</param>
        /// <param name="fieldValue">字段值数字</param>
        /// <param name="where">条件,为空更新所有内容</param>
        /// <param name="trans">事务对象</param>
        /// <returns>执行成功返回<c>true</c>，否则为<c>false</c>。</returns>
        [Obsolete("建议用SqlSugar官方的函数")]
        public virtual bool UpdateTableField(string strField, int fieldValue, string where, IDbTransaction trans = null)
        {
            if (HasInjectionData(where))
            {
                LogHelper.Info($"检测出SQL注入的恶意数据(IP:{Function.GetIPAddress()}), {where}");
                throw new Exception("检测出SQL注入的恶意数据");
            }
            if (string.IsNullOrEmpty(where))
            {
                where = "1=1";
            }
            string sql = $"update {tableName} set " + strField + "=" + fieldValue + "";
            if (!string.IsNullOrEmpty(where))
            {
                sql += " where " + where;
            }

            base.Context.Ado.ExecuteCommand(sql);
            return true;
        }

        /// <summary>
        /// 更新某一字段值，字段值为数字
        /// </summary>
        /// <param name="strField">字段</param>
        /// <param name="fieldValue">字段值数字</param>
        /// <param name="where">条件,为空更新所有内容</param>
        /// <param name="trans">事务对象</param>
        /// <returns>执行成功返回<c>true</c>，否则为<c>false</c>。</returns>
        [Obsolete("建议用SqlSugar官方的函数")]
        public virtual async Task<bool> UpdateTableFieldAsync(string strField, int fieldValue, string where, IDbTransaction trans = null)
        {
            if (HasInjectionData(where))
            {
                LogHelper.Info($"检测出SQL注入的恶意数据(IP:{Function.GetIPAddress()}), {where}");
                throw new Exception("检测出SQL注入的恶意数据");
            }
            if (string.IsNullOrEmpty(where))
            {
                where = "1=1";
            }
            string sql = $"update {tableName} set " + strField + "=" + fieldValue + "";
            if (!string.IsNullOrEmpty(where))
            {
                sql += " where " + where;
            }

            await base.Context.Ado.ExecuteCommandAsync(sql);
            return true;
        }
        #endregion

        #region 更新扩展

        /// <summary>
        /// 执行更新数据的Sql语句
        /// </summary>
        /// <param name="sql">更新数据的Sql语句</param>
        /// <returns></returns>
        public int UpdateBySql(string sql)
        {
            return base.Context.Ado.ExecuteCommand(sql);
        }

        #endregion

        #endregion

        #region 查询

        #region 单个实体

        /// <summary>
        /// 根据id获取一个对象
        /// </summary>
        /// <param name="primaryKey">主键</param>
        /// <returns></returns>
        public virtual T Get(TKey primaryKey)
        {
            return base.GetById(primaryKey);
        }
        /// <summary>
        /// 异步根据id获取一个对象
        /// </summary>
        /// <param name="primaryKey">主键</param>
        /// <returns></returns>
        public virtual async Task<T> GetAsync(TKey primaryKey)
        {
            return await base.GetByIdAsync(primaryKey);
        }
        /// <summary>
        /// 根据条件获取一个对象
        /// </summary>
        /// <param name="where">查询条件</param>
        /// <returns></returns>
        [Obsolete("建议用SqlSugar官方的函数")]
        public virtual T GetWhere(string where)
        {
            if (HasInjectionData(where))
            {
                LogHelper.Info($"检测出SQL注入的恶意数据(IP:{Function.GetIPAddress()}), {where}");
                throw new Exception("检测出SQL注入的恶意数据");
            }
            if (string.IsNullOrEmpty(where))
            {
                where = "1=1";
            }
            string sql = $"select * from { tableName} ";
            if (!string.IsNullOrWhiteSpace(where))
            {
                sql += " where " + where;
            }
            return base.Context.Ado.SqlQuerySingle<T>(sql);

        }
        /// <summary>
        /// 根据条件异步获取一个对象
        /// </summary>
        /// <param name="where">查询条件</param>
        /// <returns></returns>
        [Obsolete("建议用SqlSugar官方的函数")]
        public virtual async Task<T> GetWhereAsync(string where)
        {
            if (HasInjectionData(where))
            {
                LogHelper.Info($"检测出SQL注入的恶意数据(IP:{Function.GetIPAddress()}), {where}");
                throw new Exception("检测出SQL注入的恶意数据");
            }
            if (string.IsNullOrEmpty(where))
            {
                where = "1=1";
            }
            string sql = $"select * from { tableName} ";
            if (!string.IsNullOrWhiteSpace(where))
            {
                sql += " where " + where;
            }

            return await base.Context.Ado.SqlQuerySingleAsync<T>(sql);
        }

        #endregion

        #region 列表
        /// <summary>
        /// 获取所有数据，谨慎使用
        /// </summary>
        /// <param name="trans">事务</param>
        /// <returns></returns>
        [Obsolete("建议用SqlSugar官方的函数")]
        public virtual IEnumerable<T> GetAll(IDbTransaction trans = null)
        {
            return GetListWhere();
        }
        /// <summary>
        /// 获取所有数据，谨慎使用
        /// </summary>
        /// <param name="trans"></param>
        /// <returns></returns>
        [Obsolete("建议用SqlSugar官方的函数")]
        public virtual async Task<IEnumerable<T>> GetAllAsync(IDbTransaction trans = null)
        {
            return await GetListWhereAsync();
        }

        /// <summary>
        /// 根据查询条件获取数据集合
        /// </summary>
        /// <param name="where">查询条件</param>
        /// <param name="fieldToSort">排序字段</param>
        /// <param name="desc">是否降序</param>
        /// <param name="trans">事务对象</param>
        /// <returns></returns>
        [Obsolete("建议用SqlSugar官方的函数")]
        public virtual IEnumerable<T> GetListWhere(string where = null, string fieldToSort = null, bool desc = true, IDbTransaction trans = null)
        {
            if (HasInjectionData(where))
            {
                LogHelper.Info($"检测出SQL注入的恶意数据(IP:{Function.GetIPAddress()}), {where}");
                throw new Exception("检测出SQL注入的恶意数据");
            }
            string sql = $"select {selectedFields} from { tableName} ";
            if (!string.IsNullOrWhiteSpace(where))
            {
                sql += " where " + where;
            }
            if (!string.IsNullOrWhiteSpace(fieldToSort))
            {
                sql += string.Format(" order by {0} {1}", fieldToSort, desc ? "DESC" : "ASC");
            }

            return base.Context.Ado.SqlQuery<T>(sql);
        }

        /// <summary>
        /// 根据查询条件获取数据集合
        /// </summary>
        /// <param name="where">查询条件</param>
        /// <param name="fieldToSort">排序字段</param>
        /// <param name="desc">是否降序</param>
        /// <param name="trans">事务对象</param>
        /// <returns></returns>
        [Obsolete("建议用SqlSugar官方的函数")]
        public virtual async Task<IEnumerable<T>> GetListWhereAsync(string where = null, string fieldToSort = null, bool desc = true, IDbTransaction trans = null)
        {
            if (HasInjectionData(where))
            {
                LogHelper.Info($"检测出SQL注入的恶意数据(IP:{Function.GetIPAddress()}), {where}");
                throw new Exception("检测出SQL注入的恶意数据");
            }
            string sql = $"select {selectedFields}  from { tableName} ";
            if (!string.IsNullOrWhiteSpace(where))
            {
                sql += " where " + where;
            }
            if (!string.IsNullOrWhiteSpace(fieldToSort))
            {
                sql += string.Format(" order by {0} {1}", fieldToSort, desc ? "DESC" : "ASC");
            }
            return await base.Context.Ado.SqlQueryAsync<T>(sql);
        }

        /// <summary>
        /// 根据查询条件查询前多少条数据
        /// </summary>
        /// <param name="top">多少条数据</param>
        /// <param name="where">查询条件</param>
        /// <param name="fieldToSort">排序字段</param>
        /// <param name="desc">是否降序</param>
        /// <param name="trans">事务对象</param>
        /// <returns></returns>
        [Obsolete("建议用SqlSugar官方的函数")]
        public virtual IEnumerable<T> GetListTopWhere(int top, string where = null, string fieldToSort = null, bool desc = true, IDbTransaction trans = null)
        {
            if (HasInjectionData(where))
            {
                LogHelper.Info($"检测出SQL注入的恶意数据(IP:{Function.GetIPAddress()}), {where}");
                throw new Exception("检测出SQL注入的恶意数据");
            }
            string sql = $"select top {top} {selectedFields} from " + tableName; ;
            if (curDbType == global::SqlSugar.DbType.SqlServer)
            {
                if (!string.IsNullOrWhiteSpace(where))
                {
                    sql += " where " + where;
                }
                if (!string.IsNullOrWhiteSpace(fieldToSort))
                {
                    sql += string.Format(" order by {0} {1}", fieldToSort, desc ? "DESC" : "ASC");
                }
            }
            else if (curDbType == global::SqlSugar.DbType.MySql)
            {
                sql = $"select {selectedFields} from " + tableName;

                if (!string.IsNullOrWhiteSpace(where))
                {
                    sql += " where " + where;
                }
                if (!string.IsNullOrWhiteSpace(fieldToSort))
                {
                    sql += string.Format(" order by {0} {1}", fieldToSort, desc ? "DESC" : "ASC");
                }
                sql += $"  LIMIT 0,{top}; ";
            }

            return base.Context.Ado.SqlQuery<T>(sql);
        }

        /// <summary>
        /// 根据查询条件查询前多少条数据
        /// </summary>
        /// <param name="top">多少条数据</param>
        /// <param name="where">查询条件</param>
        /// <param name="fieldToSort">排序字段</param>
        /// <param name="desc">是否降序</param>
        /// <param name="trans">事务对象</param>
        /// <returns></returns>
        [Obsolete("建议用SqlSugar官方的函数")]
        public virtual async Task<IEnumerable<T>> GetListTopWhereAsync(int top, string where = null, string fieldToSort = null, bool desc = true, IDbTransaction trans = null)
        {
            if (HasInjectionData(where))
            {
                LogHelper.Info($"检测出SQL注入的恶意数据(IP:{Function.GetIPAddress()}), {where}");
                throw new Exception("检测出SQL注入的恶意数据");
            }
            string sql = $"select top {top} {selectedFields} from " + tableName;
            if (curDbType == global::SqlSugar.DbType.SqlServer)
            {
                if (!string.IsNullOrWhiteSpace(where))
                {
                    sql += " where " + where;
                }
                if (!string.IsNullOrWhiteSpace(fieldToSort))
                {
                    sql += string.Format(" order by {0} {1}", fieldToSort, desc ? "DESC" : "ASC");
                }
            }
            else if (curDbType == global::SqlSugar.DbType.MySql)
            {
                sql = $"select {selectedFields} from " + tableName;

                if (!string.IsNullOrWhiteSpace(where))
                {
                    sql += " where " + where;
                }
                if (!string.IsNullOrWhiteSpace(fieldToSort))
                {
                    sql += string.Format(" order by {0} {1}", fieldToSort, desc ? "DESC" : "ASC");
                }
                sql += $"  LIMIT 0,{top}; ";
            }

            return await base.Context.Ado.SqlQueryAsync<T>(sql);
        }

        /// <summary>
        /// 根据条件查询数据库,并返回对象集合(用于分页数据显示)
        /// </summary>
        /// <param name="condition">查询的条件</param>
        /// <param name="info">分页实体</param>
        /// <param name="trans">事务对象</param>
        /// <returns>指定对象的集合</returns>
        [Obsolete("建议用SqlSugar官方的函数")]
        public virtual List<T> FindWithPager(string condition, PagerInfo info, IDbTransaction trans = null)
        {
            return FindWithPager(condition, info, this.SortField, this.isDescending, trans);
        }

        /// <summary>
        /// 根据条件查询数据库,并返回对象集合(用于分页数据显示)
        /// </summary>
        /// <param name="condition">查询的条件</param>
        /// <param name="info">分页实体</param>
        /// <param name="fieldToSort">排序字段</param>
        /// <param name="trans">事务对象</param>
        /// <returns>指定对象的集合</returns>
        [Obsolete("建议用SqlSugar官方的函数")]
        public virtual List<T> FindWithPager(string condition, PagerInfo info, string fieldToSort, IDbTransaction trans = null)
        {
            return FindWithPager(condition, info, fieldToSort, this.isDescending, trans);
        }

        /// <summary>
        /// 根据条件查询数据库,并返回对象集合(用于分页数据显示)
        /// </summary>
        /// <param name="condition">查询的条件</param>
        /// <param name="info">分页实体</param>
        /// <param name="fieldToSort">排序字段</param>
        /// <param name="trans">事务对象</param>
        /// <returns>指定对象的集合</returns>
        [Obsolete("建议用SqlSugar官方的函数")]
        public virtual async Task<List<T>> FindWithPagerAsync(string condition, PagerInfo info, string fieldToSort, IDbTransaction trans = null)
        {
            return await FindWithPagerAsync(condition, info, fieldToSort, this.isDescending, trans);
        }

        /// <summary>
        /// 根据条件查询数据库,并返回对象集合(用于分页数据显示)
        /// </summary>
        /// <param name="condition">查询的条件</param>
        /// <param name="info">分页实体</param>
        /// <param name="trans">事务对象</param>
        /// <returns>指定对象的集合</returns>
        [Obsolete("建议用SqlSugar官方的函数")]
        public virtual async Task<List<T>> FindWithPagerAsync(string condition, PagerInfo info, IDbTransaction trans = null)
        {
            return await FindWithPagerAsync(condition, info, this.SortField, trans);
        }
        /// <summary>
        /// 根据条件查询数据库,并返回对象集合(用于分页数据显示)
        /// </summary>
        /// <param name="condition">查询的条件</param>
        /// <param name="info">分页实体</param>
        /// <param name="fieldToSort">排序字段</param>
        /// <param name="desc">排序方式 true为desc，false为asc</param>
        /// <param name="trans">事务对象</param>
        /// <returns>指定对象的集合</returns>
        [Obsolete("建议用SqlSugar官方的函数")]
        public virtual List<T> FindWithPager(string condition, PagerInfo info, string fieldToSort, bool desc, IDbTransaction trans = null)
        {

            List<T> list = new List<T>();

            if (HasInjectionData(condition))
            {
                LogHelper.Info($"检测出SQL注入的恶意数据(IP:{Function.GetIPAddress()}), {condition}");
                throw new Exception("检测出SQL注入的恶意数据");
            }
            if (string.IsNullOrEmpty(condition))
            {
                condition = "1=1";
            }
            PagerHelper pagerHelper = new PagerHelper(this.tableName, this.selectedFields, fieldToSort, info.PageSize, info.CurrenetPageIndex, desc, condition);

            string countSql = pagerHelper.GetPagingSql(curDbType, true);

            string pageSql = pagerHelper.GetPagingSql(curDbType, false);


            info.RecordCount = base.Context.Ado.GetInt(countSql);

            list = base.Context.Ado.SqlQuery<T>(pageSql);

            return list;
        }

        /// <summary>
        /// 根据条件查询数据库,并返回对象集合(用于分页数据显示)
        /// </summary>
        /// <param name="condition">查询的条件</param>
        /// <param name="info">分页实体</param>
        /// <param name="fieldToSort">排序字段</param>
        /// <param name="desc">排序方式 true为desc，false为asc</param>
        /// <param name="trans">事务对象</param>
        /// <returns>指定对象的集合</returns>
        [Obsolete("建议用SqlSugar官方的函数")]
        public virtual async Task<List<T>> FindWithPagerAsync(string condition, PagerInfo info, string fieldToSort, bool desc, IDbTransaction trans = null)
        {

            List<T> list = new List<T>();

            if (HasInjectionData(condition))
            {
                LogHelper.Info($"检测出SQL注入的恶意数据(IP:{Function.GetIPAddress()}), {condition}");
                throw new Exception("检测出SQL注入的恶意数据");
            }
            if (string.IsNullOrEmpty(condition))
            {
                condition = "1=1";
            }

            PagerHelper pagerHelper = new PagerHelper(this.tableName, this.selectedFields, fieldToSort, info.PageSize, info.CurrenetPageIndex, desc, condition);

            string countSql = pagerHelper.GetPagingSql(curDbType, true);
            string pageSql = pagerHelper.GetPagingSql(curDbType, false);

            info.RecordCount = base.Context.Ado.GetInt(countSql);

            list = await base.Context.Ado.SqlQueryAsync<T>(pageSql);

            return list;
        }
        #endregion

        /// <summary>
        /// 根据条件统计数据
        /// </summary>
        /// <param name="condition">查询条件</param>
        /// <param name="fieldName">统计字段名称</param>
        /// <returns></returns>
        [Obsolete("建议用SqlSugar官方的函数")]
        public virtual int GetCountByWhere(string condition, string fieldName = "*")
        {
            if (HasInjectionData(condition))
            {
                LogHelper.Info($"检测出SQL注入的恶意数据(IP:{Function.GetIPAddress()}), {condition}");
                throw new Exception("检测出SQL注入的恶意数据");
            }
            if (string.IsNullOrEmpty(condition))
            {
                condition = "1=1";
            }
            string sql = $"select count({fieldName}) from {tableName}  where ";
            if (!string.IsNullOrWhiteSpace(condition))
            {
                sql = sql + condition;
            }
            return base.Context.Ado.GetInt(sql);
        }

        /// <summary>
        /// 根据条件统计数据
        /// </summary>
        /// <param name="condition">查询条件</param>
        /// <param name="fieldName">统计字段名称</param>
        /// <returns></returns>
        [Obsolete("建议用SqlSugar官方的函数")]
        public virtual async Task<int> GetCountByWhereAsync(string condition, string fieldName = "*")
        {
            if (HasInjectionData(condition))
            {
                LogHelper.Info($"检测出SQL注入的恶意数据(IP:{Function.GetIPAddress()}), {condition}");
                throw new Exception("检测出SQL注入的恶意数据");
            }
            if (string.IsNullOrEmpty(condition))
            {
                condition = "1=1";
            }
            string sql = $"select count({fieldName}) from {tableName}  where ";
            if (!string.IsNullOrWhiteSpace(condition))
            {
                sql = sql + condition;
            }
            return await base.Context.Ado.GetIntAsync(sql);
        }

        /// <summary>
        /// 根据条件查询获取某个字段的最大值
        /// </summary>
        /// <param name="strField">字段</param>
        /// <param name="where">条件</param>
        /// <param name="trans">事务</param>
        /// <returns>返回字段的最大值</returns>
        [Obsolete("建议用SqlSugar官方的函数")]
        public virtual async Task<dynamic> GetMaxValueByFieldAsync(string strField, string where, IDbTransaction trans = null)
        {
            string sql = $"select isnull(MAX({strField}),0) as maxVaule from {tableName} ";
            if (curDbType == global::SqlSugar.DbType.MySql)
            {
                sql = $"select if(isnull(MAX({strField})),0,MAX({strField})) as maxVaule from {tableName} ";
            }
            if (!string.IsNullOrEmpty(where))
            {
                sql += " where " + where;
            }

            return await base.Context.Ado.GetScalarAsync(sql);
        }
        /// <summary>
        /// 根据条件统计某个字段之和,sum(字段)
        /// </summary>
        /// <param name="strField">字段</param>
        /// <param name="where">条件</param>
        /// <param name="trans">事务</param>
        /// <returns>返回字段求和后的值</returns>
        [Obsolete("建议用SqlSugar官方的函数")]
        public virtual async Task<dynamic> GetSumValueByFieldAsync(string strField, string where, IDbTransaction trans = null)
        {
            string sql = $"select isnull(sum({strField}),0) as sumVaule from {tableName} ";
            if (curDbType == global::SqlSugar.DbType.MySql)
            {
                sql = $"select if(isnull(sum({strField})),0,sum({strField})) as sumVaule from {tableName} ";
            }
            if (!string.IsNullOrEmpty(where))
            {
                sql += " where " + where;
            }
            return await base.Context.Ado.GetScalarAsync(sql);
        }

        #region Query 查询扩展
        /// <summary>
        /// 是否存在,存在返回true，不存在返回false
        /// </summary>
        /// <param name="where"></param>
        /// <returns></returns>

        public virtual bool Exist(Expression<Func<T, bool>> @where = null)
        {
            var result = base.Count(@where);
            return result > 0;
        }
        /// <summary>
        /// 是否存在,存在返回true，不存在返回false
        /// </summary>
        /// <param name="where"></param>
        /// <returns></returns>
        public virtual async Task<bool> ExistAsync(Expression<Func<T, bool>> @where = null)
        {
            var result = await base.CountAsync(@where);
            return result > 0;
        }
        /// <summary>
        /// 获取单个实体。建议：如需使用Include和ThenInclude请重载此方法。
        /// </summary>
        /// <param name="where"></param>
        /// <param name="orderEexpression">排序字段</param>
        /// <param name="desc">是否降序</param>
        /// <returns></returns>
        public virtual T GetSingleOrDefault(Expression<Func<T, bool>> @where = null, Expression<Func<T, object>> orderEexpression = null, bool desc = true)
        {
            return base.Context.Queryable<T>().OrderByIF(orderEexpression != null, orderEexpression, desc ? OrderByType.Desc : OrderByType.Asc)
                .First(@where);
        }

        /// <summary>
        /// 获取单个实体。建议：如需使用Include和ThenInclude请重载此方法。
        /// </summary>
        /// <param name="where"></param>
        /// <param name="orderEexpression">排序字段</param>
        /// <param name="desc">是否降序</param>
        /// <returns></returns>
        public virtual async Task<T> GetSingleOrDefaultAsync(Expression<Func<T, bool>> @where = null, Expression<Func<T, object>> orderEexpression = null, bool desc = true)
        {
            return await base.Context.Queryable<T>().OrderByIF(orderEexpression != null, orderEexpression, desc ? OrderByType.Desc : OrderByType.Asc)
                .FirstAsync(@where);
        }


        /// <summary>
        /// 获取实体列表。建议：如需使用Include和ThenInclude请重载此方法。
        /// </summary>
        /// <param name="where"></param>
        /// <param name="orderEexpression">排序字段</param>
        /// <param name="desc">是否降序</param>
        /// <returns></returns>
        public virtual IEnumerable<T> Get(Expression<Func<T, bool>> @where = null, Expression<Func<T, object>> orderEexpression = null, bool desc = true)
        {
            return base.Context.Queryable<T>().OrderByIF(orderEexpression != null, orderEexpression, desc ? OrderByType.Desc : OrderByType.Asc)
                .Where(@where).ToList();
        }
        /// <summary>
        /// 获取实体列表。建议：如需使用Include和ThenInclude请重载此方法。
        /// </summary>
        /// <param name="where"></param>
        /// <param name="orderEexpression">排序字段</param>
        /// <param name="desc">是否降序</param>
        /// <returns></returns>
        public virtual async Task<IEnumerable<T>> GetAsync(Expression<Func<T, bool>> @where = null, Expression<Func<T, object>> orderEexpression = null, bool desc = true)
        {
            return await base.Context.Queryable<T>().OrderByIF(orderEexpression != null, orderEexpression, desc ? OrderByType.Desc : OrderByType.Asc)
                .Where(@where).ToListAsync();
        }

        /// <summary>
        ///  分页获取实体列表。建议：如需使用Include和ThenInclude请重载此方法。
        /// </summary>
        /// <param name="where">查询条件</param>
        /// <param name="pagerInfo">分页信息</param>
        /// <param name="asc">排序方式</param>
        /// <param name="orderby">排序字段</param>
        /// <returns></returns>
        public virtual IEnumerable<T> GetByPagination(Expression<Func<T, bool>> @where, PagerInfo pagerInfo, bool asc = false, params Expression<Func<T, object>>[] @orderby)
        {
            return null;
        }
        /// <summary>
        /// sql语句查询数据集
        /// </summary>
        /// <param name="sql"></param>
        /// <returns></returns>
        public IEnumerable<T> GetBySql(string sql)
        {
            return GetBySql<T>(sql);
        }

        /// <summary>
        /// sql语句查询数据集
        /// </summary>
        /// <param name="sql"></param>
        /// <returns></returns>
        public IEnumerable<E> GetBySql<E>(string sql)
        {
            return base.Context.Ado.SqlQuery<E>(sql);
        }

        /// <summary>
        /// sql语句查询数据集
        /// </summary>
        /// <param name="sql"></param>
        /// <returns></returns>
        public decimal GetDecimalBySql(string sql)
        {
            return base.Context.Ado.GetDecimal(sql);
        }
        #endregion

        #endregion

        #region 多表批量操作，支持事务
        /// <summary>
        /// 多表多数据操作批量插入、更新、删除--事务
        /// </summary>
        /// <param name="trans">事务</param>
        /// <param name="commandTimeout">超时</param>
        /// <returns></returns>
        public async Task<Tuple<bool, string>> ExecuteTransactionAsync(List<Tuple<string, object>> trans, int? commandTimeout = null)
        {
            throw new NotImplementedException();
        }

        /// <summary>
        /// 多表多数据操作批量插入、更新、删除--事务
        /// </summary>
        /// <param name="trans">事务</param>
        /// <param name="commandTimeout">超时</param>
        /// <returns></returns>
        public Tuple<bool, string> ExecuteTransaction(List<Tuple<string, object>> trans, int? commandTimeout = null)
        {
            throw new NotImplementedException();
        }

        #endregion

        #region 辅助类方法


        /// <summary>
        /// 验证是否存在注入代码(条件语句）
        /// </summary>
        /// <param name="inputData"></param>
        public virtual bool HasInjectionData(string inputData)
        {
            if (string.IsNullOrEmpty(inputData))
                return false;

            //里面定义恶意字符集合
            //验证inputData是否包含恶意集合
            if (Regex.IsMatch(inputData.ToLower(), GetRegexString()))
            {
                return true;
            }
            else
            {
                return false;
            }
        }

        /// <summary>
        /// 获取正则表达式
        /// </summary>
        /// <returns></returns>
        private static string GetRegexString()
        {
            //构造SQL的注入关键字符
            string[] strBadChar =
            {
                "--\\s",
                "select\\s",
                "from\\s",
                "insert\\s",
                "delete\\s",
                "update\\s",
                "drop\\s",
                "truncate\\s",
                "exec\\s",
                "count\\(",
                "declare\\s",
                "asc\\(",
                "mid\\(",
                "char\\(",
                "net user",
                "xp_cmdshell",
                "/add\\s",
                "exec master.dbo.xp_cmdshell",
                "net localgroup administrators"
            };

            //构造正则表达式
            string str_Regex = ".*(";
            for (int i = 0; i < strBadChar.Length - 1; i++)
            {
                str_Regex += strBadChar[i] + "|";
            }
            str_Regex += strBadChar[strBadChar.Length - 1] + ").*";

            return str_Regex;
        }


        #endregion

        #region IDisposable Support
        private bool disposedValue = false; // 要检测冗余调用
        /// <summary>
        /// 
        /// </summary>
        /// <param name="disposing"></param>
        protected virtual void Dispose(bool disposing)
        {
            if (!disposedValue)
            {
                if (disposing)
                {
                    // TODO: 释放托管状态(托管对象)。
                }

                // TODO: 释放未托管的资源(未托管的对象)并在以下内容中替代终结器。
                // TODO: 将大型字段设置为 null。

                disposedValue = true;
            }
        }

        // TODO: 仅当以上 Dispose(bool disposing) 拥有用于释放未托管资源的代码时才替代终结器。
        // ~BaseRepository() {
        //   // 请勿更改此代码。将清理代码放入以上 Dispose(bool disposing) 中。
        //   Dispose(false);
        // }

        /// <summary>
        /// 
        /// </summary>
        public void Dispose()
        {
            // 请勿更改此代码。将清理代码放入以上 Dispose(bool disposing) 中。
            Dispose(true);
        }
        #endregion
    }
}
